package tools;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.common.collect.Lists;

import cn.hutool.core.io.FileUtil;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

public class Html2Text {
	
	public static void main(String[] args) throws IOException {
		
		List<File> files = FileUtil.loopFiles("F:/szyz/中医宝典/zybd/中医书籍大全");
		List<Book> books = Lists.newArrayList();
		for (File file : files) {
			String name = file.getName();
			String pname = file.getParent();
			books.add(Book.builder().order(Integer.valueOf(name.substring(0, name.lastIndexOf("."))))
					.name(pname.substring(pname.lastIndexOf("\\") + 1, pname.length())).path(file.getAbsolutePath())
					.build());
		}
		books = books.stream().sorted(Comparator.comparing(Book::getOrder)).collect(Collectors.toList());
		Map<String, List<Book>> groups = books.stream().collect(Collectors.groupingBy(Book::getName));

		for (String key : groups.keySet()) {
			File file = new File("F:/zongyi/" + key + ".txt");
			PrintWriter wirter = FileUtil.getPrintWriter(file, "GBK", true);
			List<Book> yema = groups.get(key);
			wirter.append(key);
			for (Book bk : yema) {
				Document document = Jsoup.parse(new File(bk.getPath()), "GBK");
				Elements title = document.select("a[class=ch1a]");
				System.out.println(title.text());
				wirter.append(title.text());
				wirter.append("\n");
				Elements rows = document.select("div[class=cbd]"); 
				wirter.append(lineFeed(rows.text())); 
			}
			wirter.close();
		}

	}
	static int length = 30;
	public static String lineFeed(String str) {
		StringBuffer buf = new StringBuffer(); 
		return cut(str,buf).toString();
	}
	public static StringBuffer cut(String str,StringBuffer buf){
		if(str.length() <= length){
			return buf.append(str).append("\n");
		}else{
			buf.append(str.substring(0,length)).append("\n");
			return cut(str.substring(length,str.length()),buf);
		} 
	}
}

@Getter
@Setter
@Builder
@ToString
class Book {
	String path;
	String name;
	int order;
}